package cn.itsource.user.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.basic.constant.WxConstants;
import cn.itsource.basic.dto.LoginDto;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.LoginData;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.HttpUtil;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.sys.domain.Menu;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.Wxuser;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.mapper.WxuserMapper;
import cn.itsource.user.service.ILogininfoService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public AjaxResult accountLogin(LoginDto loginDto) {
        //校验空值
        if (StrUtil.isBlank(loginDto.getAccount())){
            throw new BusinessException("请输入账号！");
        }
        if (StrUtil.isBlank(loginDto.getAccount())){
            throw new BusinessException("请输入密码！");
        }
        //判断账号是否正确
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);
        if (logininfo == null){
            throw new BusinessException("账号或密码不正确！");
        }
        //判断密码是否正确
        String md5 = SecureUtil.md5(loginDto.getCheckPass() + logininfo.getSalt());
        if (!md5.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码不正确！");
        }
        //判断是否禁用
        if (!logininfo.getDisable()){
            throw new BusinessException("该账号已被封禁！");
        }
        //登录成功，将信息保存到redis
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo);
//        //放在浏览器中的localstorage
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo",logininfo);
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(map);
    }

    /** 微信扫码登录 */
    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //准备请求地址
        //通过replace将GET_ACK_URL中的一些参数替换掉
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));
        //发送请求 - 后端发送
        String jsonStr = HttpUtil.httpGet(url);
        System.out.println(url);
        //将json字符串转为json对象，获取里面的token和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        System.out.println(jsonObject);
        System.out.println(accessToken);
        System.out.println(openid);
        System.out.println("===============");
        //通过openid查询user
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //判断wxuser是否有
        if (wxuser != null){
            User user = userMapper.findOne(wxuser.getUserId());
            //两张表都有数据，说明以前注册过，直接免密登录
            if (user != null){
                Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
                //登录成功，将信息保存到redis
//                String token = UUID.randomUUID().toString();
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//                //放在浏览器中的localstorage
//                logininfo.setSalt(null);
//                logininfo.setPassword(null);
//                HashMap<String, Object> result = new HashMap<>();
//                result.put("token",token);
//                result.put("logininfo",logininfo);
                Map<String, Object> result = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(result);
            }
        }
        return AjaxResult.me().setSuccess(false).setResultObj("?accessToken="+accessToken+"&openid="+openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openid = map.get("openid");
        //校验空值
        if (StrUtil.isBlank(phone)){
            throw new BusinessException("请输入电话号码！");
        }
        if (StrUtil.isBlank(verifyCode)){
            throw new BusinessException("请输入验证码！");
        }
        //判断验证码是否正确，是否过期
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if (obj == null){
            throw new BusinessException("验证码已过期！");
        }
        if (!obj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("验证码错误！");
        }
        //组装另外三个地址
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
        //发送请求 - 后端发送
        String jsonStr = HttpUtil.httpGet(url);
        //转成wxuser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //根据phone查询user
        User user = userMapper.findByPhone(phone);
        if (user == null){
            //如果没有user，就根据phone创建user
            user = phone2User(phone);
            //再添加logininfo表
            Logininfo logininfo = new Logininfo();
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setType(1); //用户
            logininfo.setDisable(true); //启用
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        //将user_id设置到wxuser
        wxuser.setUserId(user.getId());
        //将wxuser添加到数据库
        wxuserMapper.add(wxuser);
        //做免密登录
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
        //登录成功，将信息保存到redis
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo);
//        //放在浏览器中的localstorage
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        HashMap<String, Object> result = new HashMap<>();
//        result.put("token",token);
//        result.put("logininfo",logininfo);
        Map<String, Object> result = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(result);
    }

    /** 根据phone创建user */
    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //生成盐值，再加密加盐
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(16);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    /** 将jsonStr转成wxuser对象 */
    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        //将jsonStr转成json对象
        JSONObject object = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(object.getString("openid"));
        wxuser.setNickname(object.getString("nickname"));
        wxuser.setHeadimgurl(object.getString("headimgurl"));
        wxuser.setUnionid(object.getString("unionid"));
        System.out.println(object.getString("openid"));
        System.out.println(object.getString("nickname"));
        return wxuser;
    }

    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        //1.获取logininfo对象
        if (logininfo.getType() == 0){ //管理员
            //2.获取当前登录人的菜单和权限 - 细节：管理员才获取
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            map.put("menus",menus);
            //3.将以上三个信息装到LoginData中
            loginData.setPermissions(permissions);
            loginData.setMenus(menus);
        }
        try {
            //4.获取公钥 将数据进行加密，得到jwt token
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.将jwt token传到前端 -
        // 前端就可以私钥解密拿到登录信息-显示用户名，
        // 拿到当前登录人的菜单 - 做动态菜单
        // 拿到当前登录人的权限 - 做资源权限
        //但是不好意思 - 前端没有解密 - 可以将以上三个信息和token一起传递给前端

        return map;
    }
}
